package org.simple.web.jwt.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.simple.web.jwt.service.AuthenticationService;
import org.simple.web.jwt.service.JwtService;
import org.simple.web.jwt.service.RequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 项目名称：web-web-jwt
 * 类名称：JwtAuthenticationTokenFilter
 * 类描述：JwtAuthenticationTokenFilter jwt认证过滤器
 * 创建时间：2018/4/11 16:40
 *
 * @author sisyphus   (E-mail:1620657419@qq.com)
 * @version v1.0
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private RequestService requestService;

    /**
     * 过滤器逻辑
     *
     * @param request  .
     * @param response .
     * @param chain    .
     * @throws ServletException .
     * @throws IOException      ,
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = requestService.getToken(request);
        if (jwtService.validateToken(token)) {
            String subject = jwtService.getSubjectFromToken(token);
            SecurityContextHolder.getContext().setAuthentication(authenticationService.loadAuthenticationByName(subject));
        }
        chain.doFilter(request, response);
    }


}
